<template>
  <div class="body_background">
    <!-- 登录内容 -->
    <div style="margin-top: 3%;">
      <span class="title">蓝旗</span>
      <span class="subtitle">有烦恼 &nbsp;&nbsp;&nbsp; 来蓝旗</span>
    </div>
    <div style="display: flex; justify-content: center; align-items: center;">
      <div class="box">
        <span ref="message" class="message" v-if="errorMessage">{{ errorMessage }}</span>
        <div class="tbl_login">
          <span class="yzlogin-tab" @click="switchLoginTab('yz')">验证码登录</span>
          &nbsp;&nbsp;&nbsp;
          <span class="mmlogin-tab" @click="switchLoginTab('mm')">密码登录</span>
        </div>

        <form v-if="currentForm === 'yz'" @submit.prevent="submitForm('yz')" class="yzlogin-form disper">
          <p><input type="text" placeholder="手机号" class="inpu" v-model="yzphone" /></p>
          <p class="ppp">
            <input type="text" placeholder="输入六位短信验证码" class="inpuuu" v-model="verificationCode" />
            <input type="button" value="验证码" class="inpuno" @click="sendSMS" />
          </p>
          <input class="login" type="submit" @click="login()" value="登录/注册" />
        </form>

        <form v-if="currentForm === 'mm'" @submit.prevent="submitForm('mm')" class="mmlogin-form">
          <p><input type="text" placeholder="手机号" class="inpu" v-model="mmphone" /></p>
          <p><input type="password" placeholder="请输入密码" class="inpu" v-model="password" /></p>
          <input class="login" type="submit" @click="login()" value="登录/注册" />
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import http from '@/api/http';

export default {
  name: 'Login',
  data() {
    return {
      errorMessage: '',
      yzphone: '',
      verificationCode: '',
      mmphone: '',
      password: '',
      currentForm: 'mm',
    };
  },
  // ✅ 组件挂载后：设置 body 背景图
  mounted() {
    document.body.style.backgroundColor = '#F0FFF0';
    //this.setBodyBackground();
  },
  // ✅ 组件销毁前：清除 body 背景
  beforeDestroy() {
    document.body.style.backgroundColor = '#F0FFF0';
    //this.clearBodyBackground();
  },
  methods: {
    setBodyBackground() {
      const bgImage = require('@/assets/R-C.jpg'); // 确保路径正确
      document.body.style.backgroundImage = `url('${bgImage}')`;
      document.body.style.backgroundSize = 'cover';
      document.body.style.backgroundPosition = 'center';
      document.body.style.backgroundRepeat = 'no-repeat';
      document.body.style.minHeight = '100vh';
      document.body.style.margin = '0';
      document.body.style.padding = '0';
    },
    clearBodyBackground() {
      // 清除背景
      //document.body.style.backgroundImage = '';
      // document.body.style.backgroundSize = '';
      //document.body.style.backgroundPosition = '';
      // document.body.style.backgroundRepeat = '';
      // 可选：设置主页面默认背景色
      document.body.style.backgroundColor = '#f4f5f6';
    },
    switchLoginTab(tab) {
      this.currentForm = tab;
    },
    submitForm(formType) {
      if (formType === 'yz') {
        if (!this.yzphone || !this.verificationCode) {
          this.errorMessage = "请输入电话号码或验证码";
          this.autoClearError();
          return;
        }
      } else if (formType === 'mm') {
        if (!this.mmphone || !this.password) {
          this.errorMessage = "请输入手机号或密码";
          this.autoClearError();
          return;
        }
      }
    },
    autoClearError() {
      setTimeout(() => {
        this.errorMessage = '';
      }, 3000);
    },
    sendSMS() {
      if (!this.isValidPhoneNumber(this.yzphone)) {
        this.errorMessage = "电话号码格式不正确";
        this.autoClearError();
        return;
      }
      this.errorMessage = "短信验证码发送成功！";
      this.autoClearError();
    },
    isValidPhoneNumber(phoneNumber) {
      const pattern = /^1[0-9]{10}$/;
      return pattern.test(phoneNumber);
    },
  async  login() {
      try {
       /* var data =await http.post('/api/Login/LoginByUser', {
          Username: this.mmphone,
          UserPwd: this.password
        });*/
  this.$router.push('/dashboard');
        console.log(data.message);
        var token=data.message;
        var userInfo=  this.parseJWT(token);
        console.log(userInfo);
 const user = {
      name: userInfo['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'],
      role: userInfo['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'],
      sid:  userInfo['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid']
    };

          localStorage.setItem('user', JSON.stringify(user));
           localStorage.setItem('token', token); // 同时保存 token 用于后续请求
        // var info = parseJwt(data.message);
        //console.log("jwt" + info)
        // 可选：设置主页面默认背景色

        // ✅ 登录成功，跳转主页
        this.$router.push('/dashboard');
      } catch (error) {
        console.error('Login failed:', error);
        this.errorMessage = '登录失败，请检查账号或密码';
        this.autoClearError();
      }
    },
    parseJWT(token) {
      const base64Url = token.split('.')[1];
      const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
      const jsonPayload = decodeURIComponent(
        atob(base64)
          .split('')
          .map(function (c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
          })
          .join('')
      );
      return JSON.parse(jsonPayload);
    },
  }
};
</script>

<style scoped>
/* ✅ 移除了 background-image，只保留布局 */
.body_background {
  min-height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 50px;
  box-sizing: border-box;
}

.title {
  font-size: 45px;
  display: block;
  text-align: center;
  color: dimgray;
}

.subtitle {
  margin-top: 15px;
  font-size: 20px;
  display: block;
  text-align: center;
  color: dimgray;
}

.box {
  margin-top: 60px;
  width: 650px;
  height: 350px;
  text-align: center;
  border: 1px solid white;
  background-color: white;
}

.login {
  text-align: center;
  margin-top: 5%;
  background-color: #1579DC;
  height: 50px;
  width: 200px;
  color: white;
  font-size: 30px;
}

/* 其他样式保持不变 */
.yzlogin-form,
.mmlogin-form {
  text-align: center;
}

.tbl_login {
  margin-top: 5%;
  text-align: center;
}

.yzlogin-tab,
.mmlogin-tab {
  font-size: 30px;
  color: #707070;
}

.inpu,
.inpuuu {
  outline: none;
  border: none;
  border-bottom-style: solid;
  width: 300px;
  height: 80px;
}

.ppp {
  width: 300px;
  margin: 0 auto;
}

.inpuno {
  outline: none;
  border: none;
  background-color: white;
}

.message {
  padding: 10px;
  background-color: #aa0000;
  color: #ffffff;
  border: 1px solid #ccc;
  border-radius: 10px;
}
</style>